/**
 * 
 */
package com.behealthy.android;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.behealthy.util.StringUtils;
import com.behealthy.util.Utility;
import com.example.behealthy.R;

/**
 * @author Monica
 *
 */

public class BeHealthyRegisterActivity extends FragmentActivity {
		
	private String url = "http://10.0.2.2:8080/TestDao/WsTest?wsdl";
//	private String url = "http://192.168.33.103:8080/TestDao/WsTest?wsdl";
	
	private EditText date;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				
    	final EditText fname = (EditText) findViewById(R.id.reg_firstname);
		final EditText lname = (EditText) findViewById(R.id.reg_lastname);
		final EditText email = (EditText) findViewById(R.id.reg_email);
		final EditText username = (EditText) findViewById(R.id.reg_username);		
		final EditText password = (EditText) findViewById(R.id.reg_password);

		TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
		Button register = (Button) findViewById(R.id.btnRegister);
		
		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		

		// Listening to login link
					loginScreen.setOnClickListener(new Button.OnClickListener() {
						public void onClick(View v) {
							// Switching to Register screen
							Intent i = new Intent(getApplicationContext(),
									BeHealthyLoginActivity.class);
							startActivity(i);
						}
					});

		// Listening to register new account link
		register.setOnClickListener(new Button.OnClickListener() {
			
			public void onClick(View v) {
				
				if (fname.getText().toString().equals("")
						|| lname.getText().toString().equals("")
						|| email.getText().toString().equals("")
						|| password.getText().toString().equals("")) {
					
					alertDialog.setTitle(StringUtils.ERR);
					alertDialog.setMessage(StringUtils.ERR_COMPULSORY);
		
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {

								}
							});
					alertDialog.show();

				}
				
				else { 
					
					// Check password length 
					if(password.getText().length() < 6) {
					alertDialog.setTitle(StringUtils.ERR);
					alertDialog.setMessage(StringUtils.ERR_PASSWORD_LENGTH);
					
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									
								}
							});
					alertDialog.show();
				}
					// Check first and last name are correct 
					else
						if(!check(fname.getText().toString()) || !check(lname.getText().toString())) {
							alertDialog.setTitle(StringUtils.ERR);
							alertDialog.setMessage(StringUtils.ERR_NAME);
							
							alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {

									}
								});
							alertDialog.show();
					}
				
						else {
							
							String passwordStr = password.getText().toString();
							String fnameStr = fname.getText().toString();
							String lnameStr = lname.getText().toString();
							String emailStr = email.getText().toString();
							String usernameStr = username.getText().toString();
							String passwordEncrypt = Utility.encryptPassword(passwordStr);
							SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
							Date birthdate;
							try {
								birthdate = fmt.parse(date.getText().toString()+" 00:00:00.000");
								
								String response = Utility.register(fnameStr, lnameStr, emailStr, passwordEncrypt, usernameStr, birthdate, url);
								String s = Utility.parseByDOM(response, "insertAccountResponse");
								
								alertDialog.setTitle("Message");
								
								if(s.equals("true")) 
									alertDialog.setMessage(StringUtils.SUCCESS_REGISTER);
								else alertDialog.setMessage(StringUtils.ERR_REGISTER);
								
								alertDialog.setButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int which) {

											}
										});
								alertDialog.show();
								
								fname.setText("");
								lname.setText("");
								email.setText("");
								password.setText("");
								date.setText("");
								username.setText("");
								
							} catch (ParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ParserConfigurationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (SAXException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							
							
						
						}
					
				}
			}
		});

	}
		
	private Boolean check (String s) {
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		for(int i=0; i<s.length(); i++) 
			if(!chars.contains(s.charAt(i)+"")) return false;
		return true;
	}
	
	public void selectDate(View view) {
        DialogFragment newFragment = new SelectDateFragment();
        newFragment.show(getSupportFragmentManager(), "DatePicker");
    }
    public void populateSetDate(int year, int month, int day) {
    	date = (EditText) findViewById(R.id.reg_birthdate);
    	date.setText(year+"-"+month+"-"+day);
    }
	 public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
	    	@Override
	    	public Dialog onCreateDialog(Bundle savedInstanceState) {
				final Calendar calendar = Calendar.getInstance();
				int yy = calendar.get(Calendar.YEAR);
				int mm = calendar.get(Calendar.MONTH);
				int dd = calendar.get(Calendar.DAY_OF_MONTH);
				return new DatePickerDialog(getActivity(), this, yy, mm, dd);
	    	}
	    	
	    	public void onDateSet(DatePicker view, int yy, int mm, int dd) {
	    		populateSetDate(yy, mm+1, dd);
	    	}
	    }
}
